/**
 * Copyright &copy; 2013-2016 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.modules.cms.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.persistence.Page;
import cn.net.ecode.common.service.CrudService;
import cn.net.ecode.common.utils.CacheUtils;
import cn.net.ecode.common.utils.DateUtils;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.modules.cms.dao.ArticleDao;
import cn.net.ecode.modules.cms.dao.ArticleDataDao;
import cn.net.ecode.modules.cms.entity.Article;
import cn.net.ecode.modules.cms.entity.ArticleCategory;
import cn.net.ecode.modules.cms.entity.ArticleData;
import cn.net.ecode.modules.cms.entity.Category;
import cn.net.ecode.modules.cms.entity.Site;
import cn.net.ecode.modules.cms.utils.CmsUtils;
import cn.net.ecode.modules.sys.entity.Role;
import cn.net.ecode.modules.sys.utils.CorpUtils;
import cn.net.ecode.modules.sys.utils.UserUtils;


/**
 * 文章Service
 * 
 * @author ThinkGem
 * @version 2015-11-19
 */
@Service
@Transactional(readOnly = true)
public class ArticleService extends CrudService<ArticleDao, Article> {

	@Autowired
	private ArticleDataDao articleDataDao;

	/**
	 * 获取文章
	 */
	public Article get(Article article) {
		Article entity = super.get(article);
		if (entity != null && StringUtils.isNotBlank(article.getId())) {
			entity.setArticleData(get(new ArticleData(article.getId())));
		}
		return entity;
	}

	/**
	 * 获取文章详情内容
	 */
	public ArticleData get(ArticleData articleData) {
		return articleDataDao.get(articleData);
	}

	/**
	 * 分页查询文章
	 * 
	 * @param page
	 * @param article
	 * @return
	 */
	@Override
	public Page<Article> findPage(Page<Article> page, Article article) {
		return super.findPage(page, article);
	}

	/**
	 * 分页查询文章
	 * 
	 * @param page
	 * @param article
	 * @param isDataScopeFilter
	 *            是否进行权限过滤
	 * @return
	 */
	@Transactional(readOnly = false)
	public Page<Article> findPage(Page<Article> page, Article article, boolean isDataScopeFilter) {
		// 更新过期的权重，间隔为“6”个小时
		Date updateExpiredWeightDate = (Date) CacheUtils.get("updateExpiredWeightDateByArticle");
		if (updateExpiredWeightDate == null
				|| (updateExpiredWeightDate != null && updateExpiredWeightDate.getTime() < new Date().getTime())) {
			dao.updateExpiredWeight(article);
			CacheUtils.put("updateExpiredWeightDateByArticle", DateUtils.addHours(new Date(), 6));
		}
		// 栏目不为空，不是跟栏目，则获取下栏目全部数据
		if (article.getCategory() != null && StringUtils.isNotBlank(article.getCategory().getId())
				&& !Category.ROOT_CODE.equals(article.getCategory().getId())) {
			article.setCategory(CmsUtils.getCategory(article.getCategory().getId()));
		}
		// 根据栏目授权进行权限过滤
		if (isDataScopeFilter && !article.getCurrentUser().isAdmin()) {
			List<String> roleCodeList = Lists.newArrayList();
			List<Role> roleList = article.getCurrentUser().getRoleList();
			for (Role role : roleList) {
				if (role != null) {
					roleCodeList.add(role.getRoleCode());
				}
			}
			if (article.getCategory() == null) {
				article.setCategory(new Category());
			}
			article.getCategory().setRoleCodeList(roleCodeList);
		}
		return super.findPage(page, article);
	}

	/**
	 * 根据栏目权限查询文章
	 * 
	 * @param page
	 * @param article
	 * @param b
	 * @return
	 */
	@Deprecated
	@Transactional(readOnly = false)
	public Page<Article> findAuthPage(Page<Article> page, Article article, boolean isDataScopeFilter) {
		return findPage(page, article, isDataScopeFilter);
	}

	/**
	 * 保存文章
	 */
	@Transactional(readOnly = false)
	public void save(Article article) {
		if (StringUtils.isNotBlank(article.getViewConfig())) {
			article.setViewConfig(StringEscapeUtils.unescapeHtml4(article.getViewConfig()));
		}
		// 设置内容状态
		if (String.valueOf(article.getCategoryCode()) != null) {
			Category category = CmsUtils.getCategory(article.getCategory().getId());
			// 如果栏目不需要审核，或者当前用户有审核权限，则将该内容设为发布状态
			/*
			 * if (Global.YES.equals(category.getIsAudit()) &&
			 * !UserUtils.getSubject().isPermitted("cms:article:audit")) { // 并且不是草稿状态 if
			 * (!article.getStatus().equals(Article.STATUS_DRAFT)){
			 * article.setStatus(Article.STATUS_AUDIT); } }
			 */
			// 将栏目信息设置到实体对象（全文检索需要）
			article.setCategory(category);
		} else {
			throw new RuntimeException("归属栏目不能为空。");
		}
		// 保存详细内容
		if (article.getIsNewRecord()) {
			//如果选了多个栏目，保存多个
			if (StringUtils.contains(article.getCategoryCode(), ",")) {
				String categorys[] = article.getCategoryCode().split(",");
				for (int i = 0; i < categorys.length; i++) {
					article.setCategoryCode(categorys[i]);
					article.preInsert();
					dao.insert(article);
					article.getArticleData().setId(article.getId());
					articleDataDao.insert(article.getArticleData());
				}
			}else {
				article.preInsert();
				dao.insert(article);
				article.getArticleData().setId(article.getId());
				articleDataDao.insert(article.getArticleData());
			}
			
		} else {
			article.preUpdate();
			dao.update(article);
			article.getArticleData().setId(article.getId());
			articleDataDao.update(article.getArticleData());
		}
	}

	/**
	 * 删除文章
	 * 
	 * @param article
	 * @param isRe
	 */
	@Transactional(readOnly = false)
	public void delete(Article article, Boolean isRe) {
		article.setStatus(
				isRe != null && isRe ? (UserUtils.getSubject().isPermitted("cms:article:audit") ? Article.STATUS_NORMAL
						: Article.STATUS_AUDIT) : Article.STATUS_DELETE);
		dao.updateStatus(article);
	}

	/**
	 * 通过编号获取内容标题
	 * 
	 * @return new Object[]{栏目Id,内容Id,内容标题}
	 */
	public List<Object[]> findByIds(String ids) {
		if (ids == null) {
			return new ArrayList<Object[]>();
		}
		List<Object[]> list = Lists.newArrayList();
		String[] idss = StringUtils.split(ids, ",");
		List<Article> l = dao.findByIdIn(idss);
		for (Article e : l) {
			list.add(new Object[] { e.getCategory().getId(), e.getId(), StringUtils.abbr(e.getTitle(), 50) });
		}
		return list;
	}

	/**
	 * 点击数加一
	 */
	@Transactional(readOnly = false)
	public void updateHitsAddOne(String id) {
		dao.updateHitsAddOne(id);
	}

	/**
	 * 获取通知公告
	 * 
	 * @param page
	 * @param article
	 * @return
	 */
	public List<Article> findNoticeList(Page<Article> page, Article article) {
		page.setPageSize(10);
		article.setCategoryCode(ArticleCategory.NOTICE.getIndex());
		return super.findPage(page, article).getList();
	}

	/**
	 * 获取新闻咨询
	 * 
	 * @param page
	 * @param article
	 * @return
	 */
	public List<Article> findNewsList(Page<Article> page, Article article) {
		page.setPageSize(10);
		article.setCategoryCode(ArticleCategory.NEWS.getIndex());
		return super.findPage(page, article).getList();
	}

	/**
	 * 获取政策法规
	 * 
	 * @param page
	 * @param article
	 * @return
	 */
	public List<Article> findPolicieList(Page<Article> page, Article article) {
		page.setPageSize(10);
		article.setCategoryCode(ArticleCategory.POLICIE.getIndex());
		return super.findPage(page, article).getList();
	}

	/**
	 * 获取文体活动 改为基层工作
	 * 
	 * @param page
	 * @param article
	 * @return
	 */
	public List<Article> findActivityList(Page<Article> page, Article article) {
		page.setPageSize(10);
		article.setCategoryCode(ArticleCategory.WORK.getIndex());
		return super.findPage(page, article).getList();
	}

	/**
	 * 增加点击数
	 * 
	 * @param id
	 */
	@Transactional(readOnly = false)
	public void addhits(String id) {
		dao.addhits(id);

	}

	/**
	 * 获取活动图片
	 * 
	 * @param page
	 * @param aritcle
	 * @return
	 */
	public List<Article> findPictureList(Page<Article> page, Article article) {
		page.setPageSize(30);
		article.setCategoryCode(ArticleCategory.PICTURE.getIndex());
		return super.findPage(page, article).getList();
	}
	/**
	 * 详情页分页是每9个一页
	 * @param page
	 * @param article
	 * @return
	 */
	public List<Article> findPictureList2(Page<Article> page, Article article) {
		page.setPageSize(9);
		article.setCategoryCode(ArticleCategory.PICTURE.getIndex());
		return super.findPage(page, article).getList();
	}

	/**
	 * 获取图片新闻
	 * 
	 * @param page
	 * @param aritcle
	 * @return
	 */
	public List<Article> findPictureNewList(Page<Article> page, Article article) {
		page.setPageSize(5);
		article.setCategoryCode(ArticleCategory.PICNEWS.getIndex());
		return super.findPage(page, article).getList();
	}

}
